function search() {
  let input = document.getElementById("myInput");
  let filter = input.value.toUpperCase();
  let table = document.getElementById("myTable");
  let tr = table.querySelectorAll("tr");
  // 循环表格每一行，查找匹配项
  for (let i = 0; i < tr.length; i++) {
    let td = tr[i].querySelectorAll("td")[0]; //获得第一列（公司名称）
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}
let input = document.getElementById("myInput");
input.addEventListener("input", search);

/* 作业内容：点击表头对表格进行排序，第一次点击时，排序为升序（A 到 Z），再次点击，排序为降序（Z 到 A） */
function sortTable(n) {
  let table = document.getElementById("myTable");
  let tr = table.querySelectorAll("tr");
  let count = 0;
  // 升序优先
  for (let i = 0; i < tr.length - 2; ++i) {
    for (let j = 1; j < tr.length - 1 - i; ++j) {
      let x = tr[j].querySelectorAll("td")[n];
      let y = tr[j + 1].querySelectorAll("td")[n];
      if (x.innerHTML.toUpperCase() > y.innerHTML.toUpperCase()) {
        tr[j].parentNode.insertBefore(tr[j + 1], tr[j]);
        tr = table.querySelectorAll("tr");
        count++;
      }
    }
  }
  //降序
  if (count == 0) {
    for (let i = 0; i < tr.length - 2; ++i) {
      for (let j = 1; j < tr.length - 1 - i; ++j) {
        let x = tr[j].querySelectorAll("td")[n];
        let y = tr[j + 1].querySelectorAll("td")[n];
        if (x.innerHTML.toUpperCase() < y.innerHTML.toUpperCase()) {
          tr[j].parentNode.insertBefore(tr[j + 1], tr[j]);
          tr = table.querySelectorAll("tr");
        }
      }
    }
  }
}
let company = document.querySelector(".header th");
let country = document.querySelector(".header th:last-child");
company.style.cursor = "pointer";
country.style.cursor = "pointer";
company.addEventListener("click", () => {
  sortTable(0);
});
country.addEventListener("click", () => {
  sortTable(1);
});
